import React, { useRef, useEffect, useState } from 'react';
import { useDispatch, useSelector } from "react-redux";
import { updataText, setCurrItemId1 } from "../store/module/listSlice";
import './index.css';

function Parent(props) {
    const cId = useSelector((state) => state.list.currentCptId);
    const maxMoveWidth = useRef({ maxWidth: 0, maxHeight: 0 });
    const editorWrapper = useRef();
    const dispatcher = useDispatch();
    const { children, style, id } = props;
    const [gap, setGap] = useState({ x: 0, y: 0 });
    const [isDragging, setIsDragging] = useState(false);
    const [isResizing, setIsResizing] = useState(false);
    const [resizeDirection, setResizeDirection] = useState(null);

    useEffect(() => {
        const { width: w, height: h } = style;
        const rect = document.querySelector('.center').getBoundingClientRect();
        maxMoveWidth.current = { maxWidth: rect.width - w, maxHeight: rect.height - h };
    }, [style]);

    const mouseDown = (event) => {
        if (event.target.closest('.v-text')) return;
        event.preventDefault();
        const currentElement = editorWrapper.current;

        if (currentElement) {
            const { left: x1, top: y1 } = currentElement.getBoundingClientRect();
            setGap({
                x: event.clientX - x1,
                y: event.clientY - y1,
            });
            setIsDragging(true);
        }

        const mousemove = (e) => {
            if (!isDragging) return;
            const { left, top } = countLocation(e);
            dispatcher(updataText({ left, top }));
        };


        const mouseup = () => {
            if (isDragging) {
                setIsDragging(false);
            } else if (isResizing) {
                setIsResizing(false);
            }
            document.removeEventListener('mousemove', mousemove);
            document.removeEventListener('mouseup', mouseup);
        };

        document.addEventListener('mousemove', mousemove);
        document.addEventListener('mouseup', mouseup);
        dispatcher(setCurrItemId1(id));
    };

    const countLocation = (e) => {
        const container = document.querySelector('.center');
        const { left: containerLeft, top: containerTop, width: containerWidth, height: containerHeight } = container.getBoundingClientRect();
        const element = editorWrapper.current;
        const { width: elementWidth, height: elementHeight } = element ? element.getBoundingClientRect() : { width: 0, height: 0 };

        let newLeft = e.clientX - containerLeft - gap.x;
        let newTop = e.clientY - containerTop - gap.y;

        newLeft = Math.max(0, Math.min(newLeft, containerWidth - elementWidth));
        newTop = Math.max(0, Math.min(newTop, containerHeight - elementHeight));

        return { left: newLeft, top: newTop };
    };


    let isDragging1 = false; // 标志变量

    const startResize = (direction, e) => {
        isDragging1 = true; // 开始拖拽
        const currentElement = editorWrapper.current;
        const { left, right, top, bottom } = currentElement.getBoundingClientRect();

        const mousemove = (e) => {
            if (!isDragging) return; // 如果不是拖拽状态，直接返回
            const size = caculateSize(direction, e, { left, right, top, bottom });
            const { style } = currentElement;
            if (size) {
                style.width = size.width + 'px';
                style.height = size.height + 'px';
                if (size.left) {
                    style.left = size.left + 'px';
                }
                if (size.top) {
                    style.top = size.top + 'px';
                }
            }
        };

        const mouseup = () => {
            isDragging1 = false; // 结束拖拽

            // 解绑事件
            document.removeEventListener('mousemove', mousemove);
            document.removeEventListener('mouseup', mouseup);
        };

        // 绑定事件
        document.addEventListener('mousemove', mousemove);
        document.addEventListener('mouseup', mouseup);

        e.stopPropagation();
    };

    // 计算尺寸的函数
    const caculateSize = (direction, e, positions) => {
        const { clientX, clientY } = e;
        const { left, right, top, bottom } = positions;
        const container = document.querySelector('.center');
        const { left: x1, top: y1 } = container.getBoundingClientRect();
        const rightWidth = clientX - left;
        const leftWidth = right - clientX;
        const bottomHeight = clientY - top;
        const topHeight = bottom - clientY;
        const topOffset = clientY - y1;
        const leftOffset = clientX - x1;

        switch (direction) {
            case 'top-left':
                return {
                    width: leftWidth,
                    height: topHeight,
                    top: topOffset,
                    left: leftOffset,
                };
            case 'top-right':
                return {
                    width: rightWidth,
                    height: topHeight,
                    top: topOffset,
                };
            case 'bottom-left':
                return {
                    width: leftWidth,
                    height: bottomHeight,
                    left: leftOffset,
                };
            case 'bottom-right':
                return {
                    width: rightWidth,
                    height: bottomHeight,
                };
            default:
                return null;
        }
    };


    return (
        <div
            ref={editorWrapper}
            className={`editItem ${id === cId ? 'active' : ''}`}
            onMouseDown={mouseDown}
            style={{
                ...style,
                cursor: 'grab',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                position: 'relative',
                overflow: 'hidden'
            }}
        >
            <span>{children}</span>
            {/* Resize corners */}
            <div className="resizers">
                <div
                    className="resizer top-left"
                    onMouseDown={(e) => { startResize('top-left', e) }}
                ></div>
                <div
                    className="resizer top-right"
                    onMouseDown={(e) => { startResize('top-right', e) }}
                ></div>
                <div
                    className="resizer bottom-left"
                    onMouseDown={(e) => { startResize('bottom-left', e) }}
                ></div>
                <div
                    className="resizer bottom-right"
                    onMouseDown={(e) => { startResize('bottom-right', e) }}
                ></div>
            </div>
        </div>
    );
}

export default Parent;
